package main

import (
	"fmt"
	"github.com/elliotchance/orderedmap/v3"

	"maps"
	"math/rand"
	"slices"
	_ "strconv"
	"sync"
)

func main() {
	//ordinaryMap()
	//OrderedMap()
	//normalMapErr01()
	//normalMapErr02()
	testRWMap()

}

func ordinaryMap() {
	var m = make(map[string]int)
	m["a"] = 0
	fmt.Printf("a=%d; b=%d\n", m["a"], m["b"])

	av, aExisted := m["a"]
	bv, bExisted := m["b"]
	fmt.Printf("a=%d, aExisted: %t; b=%d, bExisted: %t\n", av, aExisted, bv, bExisted)
}

// OrderedMap
//
//	@Description: https://github.com/elliotchance/orderedmap
func OrderedMap() {
	m := orderedmap.NewOrderedMap[string, any]()
	m.Set("foo", "bar")
	m.Set("qux", 1.23)
	m.Set("123", true)

	m.Delete("qux")
	fmt.Println(slices.Collect(m.Keys()))       //[foo 123]
	fmt.Println(maps.Collect(m.AllFromFront())) //map[123:true foo:bar]
	for el := m.Front(); el != nil; el = el.Next() {
		fmt.Println(el.Key, el.Value)
	}
	//foo bar
	//123 true

}

// normalMapErr01
//
//	@Description: map错误一： 没有初始化
func normalMapErr01() {
	var m map[string]int
	m["a"] = 0
}

// normalMapErr02
//
//	@Description: map错误二：并发读写
func normalMapErr02() {
	var m map[string]int = make(map[string]int, 10)
	go func() {
		for {
			m["a"] = 0
		}
	}()
	go func() {
		for {
			fmt.Println(m["a"])
		}
	}()

	select {}
}

type MyMap struct {
	sync.RWMutex
	m map[string]int
}

// Get
//
//	@Description: 获取值-读锁
//	@receiver m
//	@param key
//	@return int
func (m *MyMap) Get(key string) int {
	m.RLock()
	defer m.RUnlock()
	return m.m[key]
}

// Set
//
//	@Description: 设置值-互斥锁
//	@receiver m
//	@param key
//	@param value
func (m *MyMap) Set(key string, value int) {
	m.Lock()
	defer m.Unlock()
	m.m[key] = value
}

// NewRWMap
//
//	@Description: new
//	@param n
//	@return *MyMap
func NewRWMap(n int) *MyMap {
	return &MyMap{
		m: make(map[string]int, n),
	}
}

// testRWMap
//
//	@Description: 测试自己定义的读写锁map
func testRWMap() {
	m := NewRWMap(10)
	go func() {
		for {
			m.Set("key", rand.Intn(10))
		}
	}()

	go func() {
		for {
			println(m.Get("key"))
		}
	}()
	select {}
}
